<?php
namespace App\Services\Search;

use App\Models\SearchRecordModel;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;

class SearchService
{

    /**
     * @param int $uid
     * @return Builder[]|Collection
     */
    public function getSearchRecords(int $uid)
    {
        return SearchRecordModel::query()->where('user_id', $uid)
            ->select('id','keyword','updated_at')
            ->orderBy('updated_at','desc')
            ->limit(20)
            ->get();
    }

    /**
     * 创建记录
     * @param User $user
     * @param string|null $keyword
     * @return void
     */
    public static function store(User $user,string|null $keyword):void
    {
        if (!$keyword)return;
        // 创建搜索记录
        SearchRecordModel::query()->updateOrCreate(
            [
                'user_id'=>$user->id,
                'keyword'=>$keyword
            ],
            [
                'updated_at'=>now(),
            ]
        );
    }

    public function delete(User $user,int $id)
    {
//        return SearchRecordModel::query()->where('user_id',$user->id)->where('id', $id)->delete();
        return SearchRecordModel::query()->where('user_id',$user->id)->delete();
    }
}
